import React, { useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom';
import {
  Breadcrumb,
  Form,
  Input,
  Button,
  Spin,
  Tabs,
  message,
  Upload,
} from 'antd';
import md5 from 'md5';
import Api, { Url } from '../../../util/apiUrl.js';
import style from './index.module.css';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
// const { Content } = Layout;
const { TabPane } = Tabs;

const layout = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 3,
    span: 16,
  },
};

const PersonalInfo = (props) => {
  console.log('个人信息props', props);

  const [isLoading, setIsLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [loading, setLoading] = useState(false);
  // const [imgBase64, setImgBase64] = useState('');
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    getPersonalInfo();
  }, []);

  const myInfo = {};
  const getPersonalInfo = () => {
    Api.getPersonalInfo()
      .then((res) => {
        console.log('获取到的个人信息res', res);
        formInfo.setFieldsValue(res.data[0]);
        // 头像
        let avatarys = res.data[0].avatar.split('.')
        avatarys[avatarys.length-2] +='ys'
        avatarys=avatarys.join('.')

        setImageUrl(avatarys);
        // 将头像url存入储存
        window.localStorage.setItem('avatar', avatarys)
      })
      .catch((e) => {
        console.log('err', e);
      });
  };

  const [formPassword] = Form.useForm();
  const passwordOnFinish = (values) => {
    console.log('修改密码Success:', values);
    if (values.password !== values.password2) {
      message.error('两次新密码不一致');
      return false;
    } else if (values.originalPassword === values.password) {
      message.error('新旧密码相同');
      return false;
    } else {
      values = {
        password: md5(values.password),
        password2: md5(values.password2),
        account: values.account,
        originalPassword: md5(values.originalPassword),
      };
      console.log('加密后', values);
      Api.alertPassword(values)
        .then((res) => {
          console.log('修改密码返回', res);
          if (res.data.isLogin) {
            message.error('修改失败: ' + res.data.msg);
          } else {
            message.success('修改成功');
            props.history.push('/login/');
          }
        })
        .catch((err) => {
          console.log('修改密码错误', err);
        });
    }
  };
  const passwordOnFinishFailed = (errorInfo) => {
    console.log('修改密码Failed:', errorInfo);
  };

  const [formInfo] = Form.useForm();
  const infoOnFinish = async (values) => {
    console.log('个人信息Success:', values);
    values.id = 1;
    // values.avatarBase64 = imgBase64;
    values.avatar = fileList.map((i) => i.reallyUrl).join(',');
    setIsLoading(true);
    Api.alertPersonalInfo(values)
      .then((res) => {
        console.log('提交成功', res);
        setIsLoading(false);
        message.success('修改信息成功');
      })
      .catch((err) => {
        console.log('提交失败', err);
        setIsLoading(false);
        message.error('修改信息失败');
      });
  };
  const infoOnFinishFailed = (errorInfo) => {
    console.log('个人信息Failed:', errorInfo);
  };

  // tags点击
  const tabsChange = (e) => {
    console.log('tags点击', e);
  };

  // 头像处理
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
    // reader.onload = () => {
    //   setImgBase64(reader.result);
    // };
    // console.log('base64', reader.readAsDataURL(img));
  }

  function beforeUpload(file) {
    const isJpgOrPng =
      file.type === 'image/jpeg' || 'image/jpg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  const handleChange = (info) => {
    console.log('info', info);
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map((file, idx) => {
      if (file.response) {
        file.url = Url.replace('/admin/', '') + file.response[0].url;
        file.reallyUrl =
          Url.replace('/admin/', '') +
          '/public/admin/avatar/' +
          file.response[0].wsName;
      }
      return file;
    });
    setFileList(fileList);
    console.log('fileList', fileList);

    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      getBase64(
        info.file.originFileObj,
        (imageUrl) => setImageUrl(imageUrl),
        setLoading(false)
      );
    }
  };

  // 上传的配置
  // const uploadHandleChange = async (info) => {
  //   console.log('info', info);
  //   let fileList = [...info.fileList];
  //   fileList = fileList.slice(-1);
  //   fileList = fileList.map((file,idx) => {
  //     if (file.response) {
  //       file.url = Url.replace('/admin/', '') + file.response[0].url;
  //       file.reallyUrl = Url.replace('/admin/', '') +'/public/admin/liveImg/' + file.response[0].wsName
  //     }
  //     return file;
  //   });
  // }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">Upload</div>
    </div>
  );

  return (
    <>
      {isLoading ? (
        <div className={style.container}>
          <Spin size="large" className={style.spin} />
        </div>
      ) : null}
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item>Home</Breadcrumb.Item>
        <Breadcrumb.Item>个人信息</Breadcrumb.Item>
      </Breadcrumb>
      {/* <Content
        className="site-layout-background"
        style={{
          // padding: 24,
          margin: 0,
          minHeight: 280,
        }}
      > */}
      {/* 个人信息 */}
      <Tabs defaultActiveKey="1" onChange={tabsChange}>
        <TabPane tab="信息修改" key="1">
          <Form
            form={formInfo}
            {...layout}
            name="infoAlert"
            initialValues={myInfo}
            onFinish={infoOnFinish}
            onFinishFailed={infoOnFinishFailed}
          >
            <Form.Item
              label="名称"
              name="name"
              // rules={[
              //   {
              //     required: true,
              //     message: 'Please input your username!',
              //   },
              // ]}
            >
              <Input placeholder="请输入要显示的博主名称" />
            </Form.Item>

            <Form.Item label="头像" name="avatar">
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={Url + 'upImgToTemporary'}
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>

            <Form.Item
              label="技能及简要信息"
              name="skillType"
              // rules={[
              //   {
              //     required: true,
              //     message: 'Please input your password!',
              //   },
              // ]}
            >
              <Input placeholder="请输入个人技能和简要信息 , 多个以 | 分隔" />
            </Form.Item>
            <Form.Item
              label="个人说明"
              name="synopsis"
              // rules={[
              //   {
              //     required: true,
              //     message: 'Please input your password!',
              //   },
              // ]}
            >
              <Input.TextArea rows={4} placeholder="请输入个人说明" />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                修改
              </Button>
            </Form.Item>
          </Form>
        </TabPane>
        <TabPane tab="密码修改" key="2">
          <Form
            form={formPassword}
            {...layout}
            name="passwordAlert"
            initialValues={{ account: window.localStorage.getItem('account') }}
            onFinish={passwordOnFinish}
            onFinishFailed={passwordOnFinishFailed}
          >
            <Form.Item label="账号" name="account">
              <Input disabled />
            </Form.Item>
            <Form.Item
              label="原密码"
              name="originalPassword"
              rules={[
                {
                  required: true,
                  message: '请输入原来密码',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="新密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入新密码',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="重复新密码"
              name="password2"
              rules={[
                {
                  required: true,
                  message: '重复输入一次新密码',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                修改
              </Button>
            </Form.Item>
          </Form>
        </TabPane>
      </Tabs>
      {/* </Content> */}
    </>
  );
};

export default withRouter(PersonalInfo);
